package com.chaihu.front.filter;

import com.alibaba.fastjson.JSON;
import com.chaihu.bean.entity.common.TokenInfoDto;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.base.constants.CommonConstant;
import com.chaihu.core.factory.AuthenticationFactory;
import com.chaihu.utils.constant.ResponseConstant;
import com.chaihu.utils.exception.FilterException;
import com.chaihu.utils.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by wuxw on 2018/5/2.
 */
public class JwtFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(JwtFilter.class);

    private String[] excludedUris;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        excludedUris = filterConfig.getInitParameter("excludedUri").split(",");
    }

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
            throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        if (this.judgeIfAjax(request)) {
            res.setContentType("application/json;charset=utf-8");
        }
        String uri = request.getServletPath();
        //如果是 不能过滤的地址选择跳过
        if (isExcludedUri(uri)) {
            chain.doFilter(request, response);
            return;
        }

        String uuid = request.getHeader(CommonConstant.TRANSACTION_ID);
        if (StringUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString().replaceAll("\\-", "");
        }
        MDC.put("uuid", uuid);

        long tokenStartTime = System.currentTimeMillis();
        logger.info("front {}", uri);
        String token = "";
        try {
            //获取token
            token = this.getToken(request);
            try {
                TokenInfoDto tokenInfoDto = AuthenticationFactory.verifyToken(token);
                MDC.put(CommonConstant.LOGIN_USER_ID, tokenInfoDto.getUserId());
                logger.debug("校验token 耗时：{}", System.currentTimeMillis() - tokenStartTime);
                Map<String, String> claimsMap = new HashMap<>();
                claimsMap.put(CommonConstant.LOGIN_USER_ID, tokenInfoDto.getUserId());
                claimsMap.put(CommonConstant.LOGIN_USER_NAME, tokenInfoDto.getUserName());
                request.setAttribute("claims", claimsMap);
            } catch (Exception e) {
                //Invalid signature/claims
                logger.error("解析token 失败 ：", e);
                throw new FilterException(ResponseConstant.RESULT_CODE_NO_AUTHORITY_ERROR, "您还没有登录，请先登录");
            }
            chain.doFilter(req, res);
        } catch (FilterException e) {
            logger.error("业务处理失败", e);
            if ("POST".equals(request.getMethod())) {
                ResponseResult<String> responseResult = ResponseResult.error(e.getMessage());
                writeJson(response, JSON.toJSONString(responseResult), "UTF-8");
            } else {
                noLogin(request, response);
            }

        } catch (Exception e) {
            logger.error("业务处理失败", e);
            noLogin(request, response);
        } finally {
            logger.info("front {}，cost:{}", uri, (System.currentTimeMillis() - tokenStartTime) + "ms");
            MDC.remove("uuid");
            MDC.remove(CommonConstant.LOGIN_USER_ID);
        }
    }

    public void noLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (this.judgeIfAjax(request)) {
            response.setHeader("CONTEXTPATH", "/user.html#/pages/frame/login");//重定向目标地址
            response.setHeader("location", "/user.html#/pages/frame/login");//重定向目标地址
            response.setStatus(401);
        } else {
            //非ajax请求，直接使用重定向
            ResponseResult<String> responseResult = ResponseResult.error("您还没有登录，请登录");
            writeJson(response, JSON.toJSONString(responseResult), "UTF-8");
        }
    }

    /**
     * 是否ajax请求
     *
     * @param request
     * @return
     */
    private boolean judgeIfAjax(HttpServletRequest request) {
        String type = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(type)) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * 获取TOKEN
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) throws FilterException {
        String token = "";
        for (Cookie cookie : request.getCookies()) {
            if (CommonConstant.COOKIE_AUTH_TOKEN.equals(cookie.getName())) {
                token = cookie.getValue();
            }
        }

        if (StringUtil.isNullOrNone(token)) {
            throw new FilterException(ResponseConstant.RESULT_CODE_NO_AUTHORITY_ERROR, "您还没有登录，请先登录");
        }
        return token;
    }

    private void writeJson(HttpServletResponse response, String data, String encoding) {
        logger.info("JwtFilter: {}", data);
        //设置编码格式
        response.setContentType("application/json;charset=" + encoding);
        response.setCharacterEncoding(encoding);

        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(data);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isExcludedUri(String uri) {
        if (excludedUris == null || excludedUris.length <= 0) {
            return false;
        }
        for (String ex : excludedUris) {
            uri = uri.trim();
            ex = ex.trim();
            if (uri.toLowerCase().matches(ex.toLowerCase().replace("*", ".*"))) {
                return true;
            }
        }
        return false;
    }
}
